﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PinWin.Properties;

namespace PinWin
{
	public class ContextMenu
	{
		ContextMenuStrip menu;
		public ContextMenuStrip Create()
		{
			menu = new ContextMenuStrip();
			ToolStripMenuItem item;
			ToolStripSeparator sep;

			item = new ToolStripMenuItem();
			item.Text = "Choose app to pin";
            item.Text = "Apps";
            item.DropDownOpening += item_DropDownOpening;
			menu.Items.Add(item);
			item.DropDownItems.Add("Dummy");

			item = new ToolStripMenuItem();
			item.Text = "Use transparency";
			item.Name = "UseTransparencyItem";
            item.CheckedChanged += item_CheckedChanged;
			//item.Checked = true;
			item.CheckOnClick = true;
			menu.Items.Add(item);
			

			item = new ToolStripMenuItem();
			item.Text = "About";
			item.Click += new EventHandler(About_Click);
			menu.Items.Add(item);

			// Separator.
			sep = new ToolStripSeparator();
			menu.Items.Add(sep);

			item = new ToolStripMenuItem();
			item.Text = "Exit";
			item.Click += new System.EventHandler(Exit_Click);
			menu.Items.Add(item);

			return menu;
		}

        void item_CheckedChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem item = ((ToolStripMenuItem)sender);
            List<WindowInfo> wil = TopProcess.GetAllProcesses();
			foreach (WindowInfo wi in wil)
			{
                if (Convert.ToBoolean(WindowsMessageHelper.GetWindowLong(wi.MainWindowHandle, WindowsMessageHelper.GWL_EXSTYLE) & WindowsMessageHelper.WindowStyles.WS_EX_TOPMOST))
                {
					IntPtr hWnd = wi.MainWindowHandle;
                    IntPtr mode = WindowsMessageHelper.HWND.TOPMOST;
                    
					TopProcess.SetTopMode(this, hWnd, mode, item.Checked);
                }
            }
        }

		void item_DropDownOpening(object sender, EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			try
			{
				
				ToolStripMenuItem item = ((ToolStripMenuItem)sender);
				menu.SuspendLayout();
				item.DropDownItems.Clear();

				List<WindowInfo> wil = TopProcess.GetAllProcesses();
				foreach (WindowInfo wi in wil)
				{
					ToolStripItem subItem = item.DropDownItems.Add((wi.MainWindowTitle.Length == 0 ? wi.ProcessName : wi.MainWindowTitle), null, new EventHandler(App_Click));
					if (Convert.ToBoolean(WindowsMessageHelper.GetWindowLong(wi.MainWindowHandle, WindowsMessageHelper.GWL_EXSTYLE) & WindowsMessageHelper.WindowStyles.WS_EX_TOPMOST))
					{
						((ToolStripMenuItem)subItem).Checked = true;
					}
					Process p = Process.GetProcessById(wi.Id);
					try
					{
						Icon ico = Icon.ExtractAssociatedIcon(p.MainModule.FileName);//GetMainModuleFilepath(wi.Id)); - is slow!
						subItem.Image = ico.ToBitmap();
					}
					catch
					{ }
					subItem.Tag = wi.MainWindowHandle;
				}
				menu.ResumeLayout();
			}
			finally
			{
				Cursor.Current = Cursors.Default;
			}

		}

		private string GetMainModuleFilepath(int processId)
		{
			string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
			using (var searcher = new ManagementObjectSearcher(wmiQueryString))
			{
				using (var results = searcher.Get())
				{
					ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
					if (mo != null)
					{
						return (string)mo["ExecutablePath"];
					}
				}
			}
			return null;
		}

		void App_Click(object sender, EventArgs e)
		{
			ToolStripMenuItem item = ((ToolStripMenuItem)sender);
			IntPtr hWnd = (IntPtr)item.Tag;
			IntPtr mode = WindowsMessageHelper.HWND.TOPMOST;
			bool useTransparency = ((ToolStripMenuItem)menu.Items["UseTransparencyItem"]).Checked;
			if (item.Checked)
			{
				mode = WindowsMessageHelper.HWND.NOTOPMOST;
				
				item.Checked = false;
			}
			TopProcess.SetTopMode(this, hWnd, mode, useTransparency);
			
		}

		void About_Click(object sender, EventArgs e)
		{
			using (AboutForm b = new AboutForm())
			{
				b.ShowDialog();
			}
		}

		void Exit_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}
	}
}
